/*
 * e2Applet.java
 *
 * Created on 18 January 2008, 12:09
 */

import java.io.File;
import java.lang.Integer;
import java.util.Collections;
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/**
 *
 * @author  R.I.Platt
 */
public class e2Applet extends javax.swing.JApplet implements Runnable, ItemListener {
    e2GUIParameters param;
    e2game game;
    boolean lock_paint;
    Thread appletthread;
    JComboBox combo_puzzle;
	
    /** Initializes the applet e2Applet */
    public void init() {
        //try {
        //    java.awt.EventQueue.invokeAndWait(new Runnable() {
        //       public void run() {
                    initComponents();
                    //appletthread = new Thread(this);
                    //appletthread.start();
        //        }
        //    });
        //} catch (Exception ex) {
        //    ex.printStackTrace();
        //}
    }
    
    public void run() {
    	while(true) {
    		if (param.mode_auto == true) {
    			repaint();
    			System.out.println("main thread repainting");
    		} else {
    			System.out.println("main thread NOT repainting");
    			
    		}
    		try {
				Thread.sleep(2000);
    		}
    		catch (InterruptedException ex) {}
    	}
    }
    
    public void paint(Graphics g) {
    	if (lock_paint == false) {
    		param.redraw_piecebag = true;
    		param.redraw_boardpane = true;
    		super.paint(g);
    	}
    }
    
    public void newgame(int in_colnb, int in_rownb, String in_pieces, String in_hints) {
    	lock_paint = true;
		game = new e2game( getCodeBase() ,in_colnb ,in_rownb , in_pieces, in_hints);
		param.generate_piece_images();
        //GameBoardFP = new e2BoardPane(this);
		GameBoardFP.restart_board();
		lock_paint = false;
		repaint();
    	
    }
    
    public void itemStateChanged(ItemEvent e) {
    	Object value = combo_puzzle.getSelectedItem();
    	String puzzlesize = (String) value;
    	if (puzzlesize == "3x3") {
    		newgame(3,3,"brendan_puzzles/pieces_03x03.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "4x4") {
    		newgame(4,4,"brendan_puzzles/pieces_04x04.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "5x3") {
    		newgame(3,5,"brendan_puzzles/pieces_05x03.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "5x5") {
    		newgame(5,5,"brendan_puzzles/pieces_05x05.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "6x6") {
    		newgame(6,6,"brendan_puzzles/pieces_06x06.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "7x5") {
    		newgame(5,7,"brendan_puzzles/pieces_07x05.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "7x7") {
    		newgame(7,7,"brendan_puzzles/pieces_07x07.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "8x8") {
    		newgame(8,8,"brendan_puzzles/pieces_08x08.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "9x7") {
    		newgame(7,9,"brendan_puzzles/pieces_09x07.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "9x9") {
    		newgame(9,9,"brendan_puzzles/pieces_09x09.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "10x10") {
    		newgame(10,10,"brendan_puzzles/pieces_10x10.txt", "brendan_puzzles/no_hint.txt");
    	} else if (puzzlesize == "16x16") {
    		newgame(16,16,"e2files/e2pieces.txt", "e2files/e2hints.txt");
    		
    	}
    }
    
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
    	lock_paint = false;
        java.awt.GridBagConstraints gridBagConstraints;
		game = new e2game( getCodeBase() );
		//game = new e2game( getCodeBase() ,5 ,5 , "brendan_puzzles/pieces_05x05.txt", "brendan_puzzles/no_hint.txt");
    	param = new e2GUIParameters(this);

        BackPlan = new javax.swing.JPanel();
        Title = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        buttonStart = new javax.swing.JButton();
        buttonOpen = new javax.swing.JButton();
        buttonSave = new javax.swing.JButton();
        jLabelX = new javax.swing.JLabel();
        txtWidth = new javax.swing.JTextField();
        jLabelY = new javax.swing.JLabel();
        txtHigth = new javax.swing.JTextField();
        buttonSetBoard = new javax.swing.JButton();
        PieceBagFP = new e2PieceBagPane(this);
        GameBoardFP = new e2BoardPane(this);
        PieceBag = new JScrollPane(PieceBagFP);
        GameBoard = new JScrollPane(GameBoardFP);

        setBackground(new java.awt.Color(0, 0, 0));

        BackPlan.setBackground(new java.awt.Color(153, 153, 153));
        BackPlan.setLayout(new java.awt.GridBagLayout());

        Title.setText("E2 Java Helper");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 4, 2, 4);
        BackPlan.add(Title, gridBagConstraints);

        jToolBar1.setBackground(new java.awt.Color(153, 153, 153));
        jToolBar1.setBorder(null);
        jToolBar1.setRollover(true);
        jToolBar1.setMaximumSize(new java.awt.Dimension(13, 15));
        jToolBar1.setMinimumSize(new java.awt.Dimension(13, 15));

        buttonStart.setBackground(new java.awt.Color(153, 153, 153));
        buttonStart.setText("Manual Mode");
        buttonStart.setFocusable(false);
        buttonStart.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        buttonStart.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        buttonStart.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                buttonAutoMousePressed(evt);
            }
        });
        jToolBar1.add(buttonStart);

        buttonOpen.setBackground(new java.awt.Color(153, 153, 153));
        buttonOpen.setText("Open");
        buttonOpen.setFocusable(false);
        buttonOpen.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                buttonOpenMousePressed(evt);
            }
        });
        jToolBar1.add(buttonOpen);

        buttonSave.setBackground(new java.awt.Color(153, 153, 153));
        buttonSave.setText("Save");
        buttonSave.setFocusable(false);
        buttonSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        buttonSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        buttonSave.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                buttonSaveMousePressed(evt);
            }
        });
        jToolBar1.add(buttonSave);

        jLabelX.setText("X:");
        jToolBar1.add(jLabelX);

        txtWidth.setText("888");
        txtWidth.setMaximumSize(new java.awt.Dimension(30, 20));
        jToolBar1.add(txtWidth);

        jLabelY.setText("Y:");
        jToolBar1.add(jLabelY);

        txtHigth.setText("888");
        txtHigth.setMaximumSize(new java.awt.Dimension(30, 20));
        jToolBar1.add(txtHigth);

        buttonSetBoard.setBackground(new java.awt.Color(153, 153, 153));
        buttonSetBoard.setText("Set");
        buttonSetBoard.setFocusable(false);
        buttonSetBoard.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        buttonSetBoard.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        buttonSetBoard.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                buttonSetBoardMousePressed(evt);
            }
        });
        jToolBar1.add(buttonSetBoard);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        BackPlan.add(jToolBar1, gridBagConstraints);

        PieceBag.setBackground(new java.awt.Color(102, 102, 102));
        PieceBag.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        PieceBag.setMinimumSize(new java.awt.Dimension(param.piece_w*3, param.piece_w*10));
        PieceBag.setPreferredSize(new java.awt.Dimension( PieceBagFP.panewidth, PieceBagFP.paneheight));
        
        String [] puzzlelist =  {"3x3" , "4x4", "5x3", "5x5", "6x6", "7x5", "7x7", "8x8", "9x7", "9x9", "10x10", "16x16"};
        combo_puzzle = new JComboBox(puzzlelist);
        jToolBar1.add(combo_puzzle);

        //javax.swing.GroupLayout PieceBagLayout = new javax.swing.GroupLayout(PieceBag);
        //PieceBag.setLayout(PieceBagLayout);
        //PieceBagLayout.setHorizontalGroup(
        //    PieceBagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        //    .addGap(0, 158, Short.MAX_VALUE)
        //);
        //PieceBagLayout.setVerticalGroup(
        //    PieceBagLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        //    .addGap(0, 647, Short.MAX_VALUE)
        //);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
        gridBagConstraints.weightx = 0.3;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        BackPlan.add(PieceBag, gridBagConstraints);

        GameBoard.setBackground(new java.awt.Color(102, 102, 102));
        GameBoard.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        GameBoard.setMinimumSize(new java.awt.Dimension(20, 20));
        GameBoard.setPreferredSize(new java.awt.Dimension( GameBoardFP.panewidth, GameBoardFP.paneheight));
        //GameBoard.setLayout(new java.awt.GridLayout(16, 16));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 0.7;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        BackPlan.add(GameBoard, gridBagConstraints);

        //javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        //getContentPane().setLayout(layout);
        //layout.setHorizontalGroup(
        //    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        //    .addComponent(BackPlan, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
        //);
        //layout.setVerticalGroup(
        //    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        //    .addComponent(BackPlan, javax.swing.GroupLayout.DEFAULT_SIZE, 692, Short.MAX_VALUE)
        //);
        setPreferredSize(new java.awt.Dimension( GameBoardFP.panewidth + PieceBagFP.panewidth, GameBoardFP.paneheight));
        getContentPane().add(BackPlan);
        
        combo_puzzle.addItemListener(this);
                
    	
    }// </editor-fold>//GEN-END:initComponents

    private void buttonOpenMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonOpenMousePressed
        // TODO add your handling code here:
        File txtFile;
        FileHandler OpenFile = new FileHandler();
        txtFile = OpenFile.OpenE2piecesTxtFile();
        System.out.println("You chose to open this file: " + txtFile.getName());
        System.out.println("Path to this file: " + txtFile.getAbsolutePath());
        game.import_status(txtFile.getName());
    }//GEN-LAST:event_buttonOpenMousePressed

    private void buttonSaveMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonOpenMousePressed
        File txtFile;
        FileHandler OpenFile = new FileHandler();
        txtFile = OpenFile.OpenE2piecesTxtFile();
        System.out.println("You chose to open this file: " + txtFile.getName());
        System.out.println("Path to this file: " + txtFile.getAbsolutePath());
        game.export_status(txtFile.getName());
        System.out.println("Status saved ");
    }//GEN-LAST:event_buttonOpenMousePressed

    
    private void buttonAutoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonStartMousePressed
    	if (param.mode_auto == false) {
    		param.mode_auto = true;
            buttonStart.setText("Auto Mode");
    		game.solver.init_solver();
    		game.solver.mainthread.start();
    	} else {
    		param.mode_auto = false;
            buttonStart.setText("Manual Mode");
    		game.solver.kill();
    	}
    }

    private void buttonStartMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonStartMousePressed
        // TODO add your handling code here:
        /* Load piece in to piecebag
         *
         */
        //test of placement
    	int i, j;
        //Clear Board
        for (i = 0; i < param.colnb; i++) {
            for (j = 0; j < param.rownb; j++) {
                game.unplace_piece_at(i, j);
                //Title.repaint();
            }
        }
        //GameBoardFP.updateBoard();
        Collections.shuffle(game.unplacedpieces.list);
        //Place Matching Random Piece Down Starting From Top Left
        for (i = 0; i < param.colnb; i++) {
            for (j = 0; j < param.rownb; j++) {
                System.out.println("trying to place piece at " + i + " " + j);
                e2colorpattern temppattern = game.get_pattern_at(i, j);
                System.out.println(" pattern is " + temppattern.top + " " + temppattern.right + " " + temppattern.bottom + " " + temppattern.left);
                e2piecelist templist = game.get_unplaced_matching_pieces(temppattern);
                //Collections.shuffle(game.unplacedpieces.list);
                templist.shuffle();
                templist.restart();
                if (templist.hasNext()) {
                    e2piece temppiece = templist.next();
                    System.out.println(" found matching piece " + temppiece.id + " at " + i + " " + j);
                    System.out.println(" piece pattern is " + temppiece.top + " " + temppiece.right + " " + temppiece.bottom + " " + temppiece.left);
                    temppattern.set_rotation(0);
                    if (temppiece.is_matching_pattern_with_rotation(temppattern)) {
                        game.place_piece_at(temppiece.id, i, j, 0);
                    } else {
                        temppattern.set_rotation(1);
                        if (temppiece.is_matching_pattern_with_rotation(temppattern)) {
                            game.place_piece_at(temppiece.id, i, j, 3);
                        } else {
                            temppattern.set_rotation(2);
                            if (temppiece.is_matching_pattern_with_rotation(temppattern)) {
                                game.place_piece_at(temppiece.id, i, j, 2);
                            } else {
                                temppattern.set_rotation(3);
                                if (temppiece.is_matching_pattern_with_rotation(temppattern)) {
                                    game.place_piece_at(temppiece.id, i, j, 1);
                                }
                            }
                        }
                    }
                }/*else{
                  //Back Tracking Test
                    if(j == 0){
                        j = 15;
                        i--;                               
                    }else{
                        j--;
                    }
                    game.unplace_piece_at(i, j);
                    if(j == 0){
                        j = 15;
                        i--;                               
                    }else{
                        j--;
                    }
                }*/
                //Update Screen Test - Not Working --???
                //GameBoardFP.updateBoard();
                //repaint();
            }
        }
        repaint();
    }//GEN-LAST:event_buttonStartMousePressed

    private void buttonSetBoardMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonSetBoardMousePressed
        // TODO add your handling code here:
        /* 
         * Set board up to size as
         * set by txtWidth and txtHigh
        */
        int j,k;
        int intBoardWidth;
        int intBoardHigth;
        intBoardWidth = Integer.parseInt(txtWidth.getText());
        intBoardHigth = Integer.parseInt(txtHigth.getText());
        for(j=1; j<intBoardHigth; j++){
            for(k=1; k<intBoardWidth; k++){
                //Board placements for pieces here
            }
            
        }
        
        
    }//GEN-LAST:event_buttonSetBoardMousePressed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel BackPlan;
    private e2BoardPane GameBoardFP;
    private e2PieceBagPane PieceBagFP;
    private JScrollPane GameBoard;
    private JScrollPane PieceBag;
    private javax.swing.JLabel Title;
    private javax.swing.JButton buttonOpen;
    private javax.swing.JButton buttonSave;
    private javax.swing.JButton buttonSetBoard;
    private javax.swing.JButton buttonStart;
    private javax.swing.JLabel jLabelX;
    private javax.swing.JLabel jLabelY;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtHigth;
    private javax.swing.JTextField txtWidth;
    // End of variables declaration//GEN-END:variables
    
}
